package com.unei.guava.demo.bujingnian;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;

/**
 * Created by sunlei on 2015/1/22.
 */
public class MsgProcessStrategyFactory implements Supplier<MsgProcessStrategy> {

    @Override
    public MsgProcessStrategy get() {
        MsgProcessStrategy strategy=new MsgProcessStrategy();
        strategy.addRule(MsgRuleBuilder.when((Predicate) Predicates.alwaysTrue()).goon().then(defaultFunction()));
        strategy.addRule(MsgRuleBuilder.when(warnErrorPredicate()).goon().then(warnErrorFunction()));

        return strategy;
    }

    public Predicate<Msg> defaultPredicate(){
        return new Predicate<Msg>() {
            @Override
            public boolean apply(Msg input) {
                return true;
            }
        };
    }

    public Predicate<Msg> warnErrorPredicate(){
        return new Predicate<Msg>() {
            @Override
            public boolean apply(Msg input) {
                return input.getType()!=null&&(input.getType().equals("warn")||input.getType().equals("error"));
            }
        };
    }

    public Function<Msg,Msg> defaultFunction(){
        return new Function<Msg, Msg>() {
            @Override
            public Msg apply(Msg input) {
                return input.setContent(input.getType()+":"+input.getContent());
            }
        };
    }

    public Function<Msg,Msg> warnErrorFunction(){
        return new Function<Msg, Msg>() {
            @Override
            public Msg apply(Msg input) {
                return input.setContent("--------"+input.getContent());
            }
        };
    }


}
